#! /usr/bin/env python
# import the necessary things for OpenCV
from threading import Thread
import time

from opencv import cv
from opencv import highgui
from opencv.cv import *
from opencv.highgui import *

def hsv2rgb (hue):
    # convert the hue value to the corresponding rgb value

    sector_data = [[0, 2, 1],
                   [1, 2, 0],
                   [1, 0, 2],
                   [2, 0, 1],
                   [2, 1, 0],
                   [0, 1, 2]]
    hue *= 0.1 / 3
    sector = cv.cvFloor (hue)
    p = cv.cvRound (255 * (hue - sector))
    if sector & 1:
        p ^= 255

    rgb = {}
    rgb [sector_data [sector][0]] = 255
    rgb [sector_data [sector][1]] = 0
    rgb [sector_data [sector][2]] = p

    return cv.cvScalar (rgb [2], rgb [1], rgb [0], 0)

class ColorDetection(Thread):
	def __init__(self):
		Thread.__init__(self)
		device_no = 0
		self._window = highgui.cvNamedWindow ('Camera', highgui.CV_WINDOW_AUTOSIZE)
		self._window = highgui.cvNamedWindow ('Mask', highgui.CV_WINDOW_AUTOSIZE)
		self._capture = highgui.cvCreateCameraCapture(device_no)
		highgui.cvSetCaptureProperty (self._capture, highgui.CV_CAP_PROP_FRAME_WIDTH, 320)
		highgui.cvSetCaptureProperty (self._capture, highgui.CV_CAP_PROP_FRAME_HEIGHT, 240)
		if not self._capture:
			print "Error opening capture device"
			sys.exit (-1)
		
		# the range we want to monitor
		self.set_bounds(150, 170, 230, 250)
		
		frame = highgui.cvQueryFrame(self._capture)
		# get some properties of the frame
		self._frame_size = cv.cvGetSize(frame)
		self._hsv_image = cv.cvCreateImage(self._frame_size, 8, 3)
		self._mask_image = cv.cvCreateImage(self._frame_size, 8, 1)
		cvSetMouseCallback( 'Camera', self.on_mouse )
	
	def set_bounds(self, hmin, hmax, smin, smax, vmin=5, vmax=250):
		""" the range we want to monitor """
		self._hsv_min = cv.cvScalar (hmin, smin, vmin, 0)
		self._hsv_max = cv.cvScalar (hmax, smax, vmax, 0)
	
	def on_mouse(self, event, x, y, flags, param):
		if event == 1:
			print 'take %s %s' % (x, y, )
			f = self.frame
	
	def run(self):
		while 1:
			# capture the current image
			self.frame = highgui.cvQueryFrame(self._capture)
			if self.frame is None:
				# no image captured... end the processing
				break
			# compute the hsv version of the image 
			cv.cvCvtColor(self.frame, self._hsv_image, cv.CV_BGR2HSV)
			# compute which pixels are in the wanted range
			cv.cvInRangeS (self._hsv_image, self._hsv_min, self._hsv_max, self._mask_image)
			
			# we can now display the images
			highgui.cvShowImage ('Camera', self.frame)
			highgui.cvShowImage ('Mask', self._mask_image)
			# handle events
			k = highgui.cvWaitKey (10)
			
			time.sleep(0.01)

			if k == '\x1b':
				# user has press the ESC key, so exit
				break
			
			if k and k != -1:
				print 'key: %s' % (k, )

if __name__ == '__main__':
	worker = ColorDetection()
	worker.run()
	














